import React, { ReactNode, useEffect, useRef, useState } from 'react';
import { View } from '@tarojs/components';
import classNames from 'classnames';
import store from '@/src/store';
import './index.less';

export interface InlinePanelProps {
  //弹窗显示字段
  visible: boolean;
  //关闭弹窗方法回调
  onClose?: () => void;
  //页面自定义内容渲染
  content: ReactNode;
  // 自定义的样式
  className?: string;
  // 是否显示遮罩
  mask?: boolean;
  // 距离顶部的距离：有默认值，可以自定义传入
  top?: string;
  //是否是活动页面传过来
  activity?: boolean;
}

const ANIMATION_DURATION = 500;
const isIos: any = store.commonStore.isIos;
const InlinePanel: React.FC<InlinePanelProps> = ({
  visible,
  onClose,
  content,
  className,
  mask = false,
  activity,
  top = activity && isIos
    ? `calc(${store.commonStore.pageAreaTop}rpx + 40px)`
    : activity && !isIos
      ? `calc(${store.commonStore.pageAreaTop}rpx + 50px)`
      : `calc(${store.commonStore.pageAreaTop}rpx + 92rpx)`,
}) => {
  const panelRef = useRef<HTMLDivElement>(null);
  const [render, setRender] = useState(visible);
  const [animating, setAnimating] = useState<'enter' | 'exit' | null>(null);

  useEffect(() => {
    if (visible) {
      setRender(true);
      setAnimating('enter');
      document.body.style.overflow = 'hidden';
    } else if (render) {
      setAnimating('exit');
      document.body.style.overflow = '';
      const timer = setTimeout(() => setRender(false), ANIMATION_DURATION);
      return () => clearTimeout(timer);
    }
  }, [visible]);

  if (!render) return null;

  return (
    <>
      {mask && <View className="inline-panel-mask" onClick={onClose} />}
      <View
        ref={panelRef}
        className={classNames('inline-panel', className, {
          'slide-down': animating === 'enter',
          'slide-up': animating === 'exit',
        })}
        style={{ top }}
        onClick={(e) => e.stopPropagation()}
      >
        {content}
      </View>
    </>
  );
};

export default InlinePanel;
